﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using System.Configuration;


public partial class OrdenCargueListado : System.Web.UI.Page
{
    #region OrdenCargueDataTableCache
    private DataTable OrdenCargueDataTableCache
    {
        get
        {
            DataTable objTable = null;
            if (Cache["OrdenSalidaListado.aspx" + Session.SessionID] != null)
                objTable = (DataTable)Cache["OrdenSalidaListado.aspx" + Session.SessionID];
            return objTable;
        }
        set
        {
            if (value != null)
            {
                Cache.Insert("OrdenSalidaListado.aspx" + Session.SessionID, value, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
            }
        }
    }
    #endregion

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {


            OrdenCargueDataTableCache = null;
            bindDatosOrdenSalida();
        }
        else
        {
            if (OrdenCargueDataTableCache != null)
            {
                ASPxGridViewOrdenSalida.DataSource = OrdenCargueDataTableCache;
                ASPxGridViewOrdenSalida.DataBind();
            }
        }

    }
    #endregion

    #region StrAosId
    public string StrAosId
    {
        get
        {
            if (ViewState["StrAosId"] != null)
                return ViewState["StrAosId"].ToString();
            return "";
        }
        set { ViewState["StrAosId"] = value; }
    }
    #endregion

    #region crearContextItems
    private void crearContextItems()
    {
        try
        {
            Context.Items["StrAosId"] = StrAosId;
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }
    #endregion

    #region GetDataView
    private DataTable GetDataView(ASPxGridView grid)
    {
        DataTable dt = new DataTable();
        foreach (GridViewColumn col in grid.VisibleColumns)
        {
            GridViewDataColumn dataColumn = col as GridViewDataColumn;
            if (dataColumn == null) continue;
            dt.Columns.Add(dataColumn.FieldName);
        }
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            DataRow row = dt.Rows.Add();
            foreach (DataColumn col in dt.Columns)
                row[col.ColumnName] = grid.GetRowValues(i, col.ColumnName);
        }
        return dt;
    }
    #endregion

    #region bindDatosOrdenSalida
    private void bindDatosOrdenSalida()
    {
        try
        {
            //string strAdministradores = ConfigurationManager.AppSettings["Administradores"].ToString();
            //string[] strArregloAdministradores = strAdministradores.Split(',');


            #region Filrta el grid con por usuario




            Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);
            var datos = from a in contexto.AUT_ORDEN_SALIDAs
                        join d in contexto.AUT_VEHICULOs on a.AVE_ID_CABEZOTE equals d.AVE_ID
                        join e in contexto.AUT_VEHICULOs on a.AVE_ID_TRAILER equals e.AVE_ID
                        join f in contexto.AUT_ESTADOS_ORDEN_SALIDAs on a.AES_ID equals f.AES_ID
                        join g in contexto.AUT_PERSONALs on a.APE_ID equals g.APE_ID
                        orderby a.AOS_ID descending
                        where
                            a.AOS_ESTADO == "N" 
                        select new
                        {
                            a.AOS_ID,
                            CABEZOTE = d.AMA_PLACA,
                            d.AMA_PLACA,
                            TRAILER = e.AMA_PLACA,
                            AOS_FECHA_SOLICITUD = Convert.ToDateTime(a.AOS_FECHA_SOLICITUD).ToShortDateString(),
                            AOS_FECHA_ASIGNACION= Convert.ToDateTime(a.AOS_FECHA_ASIGNACION).ToShortDateString(),
                            AOS_FECHA_ENTREGA = Convert.ToDateTime(a.AOS_FECHA_ENTREGA).ToShortDateString(),
                            AOS_ESTADO = f.AES_NOMBRE,
                            g.APE_NOMBRE,
                            remesa = contexto.FN_CONCAT_REMESAS(a.AOS_ID),
                            remesaRemesa = contexto.FN_CONCAT_REMESAS_SIN_VINES(a.AOS_ID),
                            numeroFactura = contexto.FN_CONCAT_NUMERO_FACTURA(a.AOS_ID),
                            AVI_CLIENTE = contexto.FN_CONCAT_AVI_CLIENTE(a.AOS_ID)
                            
                        };


            if (datos == null) return;
            ASPxGridViewOrdenSalida.BeginUpdate();
            ASPxGridViewOrdenSalida.DataSource = datos;// objProductosComercialesRendimientosData.DefaultView;
            ASPxGridViewOrdenSalida.DataBind();
            ASPxGridViewOrdenSalida.EndUpdate();
            OrdenCargueDataTableCache = GetDataView(ASPxGridViewOrdenSalida);
            #endregion
            // break;
            //}
            //else
            //{
            //    #region Filrta el grid con por usuario
            //    //string strProNid = "0";
            //    //if (!String.IsNullOrEmpty(Session["USU_NIT"].ToString()))
            //    //    strProNid = Session["USU_NIT"].ToString();
            //    //Consulta a la base de datos
            //    DataClasses.DataClassesProyectosDataContext contexto = new DataClasses.DataClassesProyectosDataContext();
            //    var datos = from a in contexto.APP_PROPONENTEs
            //                join b in contexto.APP_PROYECTOs on a.PRO_ID equals b.PRO_ID_PROPONENTE
            //                where object.Equals(a.PRO_NIT, Session["USU_NIT"].ToString()) && object.Equals(b.VIG_ID, ConfigurationManager.AppSettings["IDVigencia"].ToString())
            //                select new
            //                {
            //                    b.PRO_ID,
            //                    b.PRO_NOMBRE,
            //                    b.PRO_VALOR_PROYECTO,
            //                    a.PRO_NIT,
            //                    a.PRO_CORREO_ELECTRONICO_REPRESENTANTE_LEGAL,
            //                    PRO_ESTADO = contexto.FN_ESTADO_PROYECTO(b.PRO_ESTADO),
            //                    b.PRO_NUMERO_RADICACION
            //                }
            //                ;


            //    if (datos == null) return;
            //    ASPxGridViewOrdenSalida.BeginUpdate();
            //    ASPxGridViewOrdenSalida.DataSource = datos;// objProductosComercialesRendimientosData.DefaultView;
            //    ASPxGridViewOrdenSalida.DataBind();
            //    ASPxGridViewOrdenSalida.EndUpdate();
            //    ProyectosProponentesDataTableCache = GetDataView(ASPxGridViewListadoProyectos);
            //    #endregion
            //    //break;
            //}
            //}
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            //throw;
        }
    }
    #endregion

    #region btnNuevo_Click
    protected void btnNuevo_Click(object sender, EventArgs e)
    {

        Server.Transfer("OrdenCargue.aspx?SSM_ID=44", true);
    }
    #endregion

    #region btnActualizar_Click
    protected void btnActualizar_Click(object sender, EventArgs e)
    {
        List<object> keyValues = ASPxGridViewOrdenSalida.GetSelectedFieldValues("AOS_ID");
        Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);
        try
        {
            foreach (object key in keyValues)
            {
                StrAosId = key.ToString();
            }
            crearContextItems();
            Server.Transfer("OrdenCargue.aspx?SSM_ID=44", true);
            //Response.Redirect("EntidadesAdministracion.aspx", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }
    #endregion

    #region btnRemesa_Click
    protected void btnRemesa_Click(object sender, EventArgs e)
    {
        //Pasar las tres variable para el reporte
        //Session["ESTADO"] = ddlEstadosOrden.Value.ToString();
        //Session["FECHA_INICIAL"] = txtFechaInicio.Text;
        //Session["FECHA_FINAL"] = txtFechaFinal.Text;
        string strCadenaClientes = "";
        List<object> keyValues = ASPxGridViewOrdenSalida.GetSelectedFieldValues("AOS_ID");
        try
        {
            foreach (object key in keyValues)
            {
                if (strCadenaClientes == "")
                    strCadenaClientes = key.ToString();
                else
                    strCadenaClientes = strCadenaClientes + "," + key.ToString();
            }
            Session["CLIENTES"] = strCadenaClientes;

            System.Text.StringBuilder l_msg = new System.Text.StringBuilder();
            //TODO: Revisar esta impresión.
            l_msg.Append(@"<script language=javascript>");
            l_msg.Append(@"window.open('DespachoReporte.aspx" + @"', 'VentanaImpresion','location=0, status=0, directories=0, width=800, height=600, resizable=no, hotkeys=no, scrollbars=yes, toolbar=no, menubar=no, personalbar=no');</script>");
            Response.Write(l_msg.ToString());

            //Response.Redirect("EntidadesAdministracion.aspx", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }

    }
    #endregion

    protected void btnEliminar_Click(object sender, EventArgs e)
    {
        List<object> keyValues = ASPxGridViewOrdenSalida.GetSelectedFieldValues("AOS_ID");
        try
        {
            foreach (object key in keyValues)
            {
                Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);


                //liberar los vives asociados
                var datosVinesAsociados = from b in contexto.AUT_ORDEN_SALIDA_AUT_VINs
                                          where b.AOS_ID == Convert.ToDecimal(key.ToString())
                                          select b;
                foreach (var v in datosVinesAsociados)
                {
                    contexto.AUT_ORDEN_SALIDA_AUT_VINs.DeleteOnSubmit(v);
                    contexto.SubmitChanges();
                }


                //elimna la orden
                var datos = from a in contexto.AUT_ORDEN_SALIDAs
                            where a.AOS_ID == Convert.ToDecimal(key.ToString())
                            select a;
                foreach (var v in datos)
                {
                    contexto.AUT_ORDEN_SALIDAs.DeleteOnSubmit(v);
                    contexto.SubmitChanges();
                }
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('Se eliminaron los registros Exitosamente');", true);
                bindDatosOrdenSalida();
            }

        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }

    #region btnRemesaGM_Click

    protected void btnRemesaGM_Click(object sender, EventArgs e)
    {
        
        //Pasar las tres variable para el reporte
        //Session["ESTADO"] = ddlEstadosOrden.Value.ToString();
        //Session["FECHA_INICIAL"] = txtFechaInicio.Text;
        //Session["FECHA_FINAL"] = txtFechaFinal.Text;
        string strCadenaClientes = "";
        List<object> keyValues = ASPxGridViewOrdenSalida.GetSelectedFieldValues("AOS_ID");
        try
        {
            foreach (object key in keyValues)
            {
                if (strCadenaClientes == "")
                    strCadenaClientes = key.ToString();
                else
                    strCadenaClientes = strCadenaClientes + "," + key.ToString();
            }
            Session["CLIENTES"] = strCadenaClientes;

            System.Text.StringBuilder l_msg = new System.Text.StringBuilder();
            //TODO: Revisar esta impresión.
            l_msg.Append(@"<script language=javascript>");
            l_msg.Append(@"window.open('DespachoReporteGM.aspx" + @"', 'VentanaImpresion','location=0, status=0, directories=0, width=800, height=600, resizable=no, hotkeys=no, scrollbars=yes, toolbar=no, menubar=no, personalbar=no');</script>");
            Response.Write(l_msg.ToString());

            //Response.Redirect("EntidadesAdministracion.aspx", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }

    }
    #endregion

    protected void ASPxGridViewOrdenSalida_RowCommand(object sender, ASPxGridViewRowCommandEventArgs e)
    {
        if (e.KeyValue.ToString() != "")
        {
            if (e.CommandArgs.CommandName == "cmdReporte")
            {
                PopupPanelMapa.Show();
                GoogleMapForASPNet1.GoogleMapObject.Points.Clear();
                Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);


                //You must specify Google Map API Key for this component. You can obtain this key from http://code.google.com/apis/maps/signup.html
                //For samples to run properly, set GoogleAPIKey in Web.Config file.
                GoogleMapForASPNet1.GoogleMapObject.APIKey = ConfigurationManager.AppSettings["GoogleAPIKey"];

                //Specify width and height for map. You can specify either in pixels or in percentage relative to it's container.
                GoogleMapForASPNet1.GoogleMapObject.Width = "500px"; // You can also specify percentage(e.g. 80%) here
                GoogleMapForASPNet1.GoogleMapObject.Height = "400px";

                //Specify initial Zoom level.
                GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 8;

                //Specify Center Point for map. Map will be centered on this point.
                GoogleMapForASPNet1.GoogleMapObject.CenterPoint = new GooglePoint("1", 3.78321671, -76.6397629);

                WebServiceRastrack.wsGetGPSDataReportsSoapClient obj = new WebServiceRastrack.wsGetGPSDataReportsSoapClient();


                var datos = from a in contexto.AUT_VEHICULOs
                            join b in contexto.AUT_ORDEN_SALIDAs on a.AVE_ID equals b.AVE_ID_CABEZOTE
                            
                            where  b.AOS_ID == Convert.ToDecimal(e.KeyValue.ToString()) //a.ATV_ID == 2 && a.AVE_FECHA_COMPRA != null
                            select a;
                foreach (var v in datos)
                {

                    WebServiceRastrack.cDataLastReportVehicle objDataPlaca = obj.wmGetGPSDataReport(v.AMA_PLACA);

                    GooglePoint GP1 = new GooglePoint();
                    if (objDataPlaca.p_fLatitude != 0)
                    {
                        GP1.ID = v.AMA_PLACA;
                        GP1.Latitude = objDataPlaca.p_fLatitude;

                        GP1.Longitude = objDataPlaca.p_fLongitude;
                        //Consulta los vines relacionados y trailer relacionado con ese cabezote
                        var datosOrden = from a in contexto.AUT_ORDEN_SALIDAs
                                         // join b in contexto.AUT_CLIENTEs on a.ACL_ID_ORIGEN equals b.ACL_ID
                                         // join c in contexto.AUT_CLIENTEs on a.ACL_ID_DESTINO equals c.ACL_ID
                                         join d in contexto.AUT_VEHICULOs on a.AVE_ID_CABEZOTE equals d.AVE_ID
                                         join r in contexto.AUT_VEHICULOs on a.AVE_ID_TRAILER equals r.AVE_ID
                                         join f in contexto.AUT_ESTADOS_ORDEN_SALIDAs on a.AES_ID equals f.AES_ID
                                         join p in contexto.AUT_PERSONALs on a.APE_ID equals p.APE_ID

                                         where
                                               d.AMA_PLACA == v.AMA_PLACA// && f.AES_ID == 1
                                         //    e.TEA_AREA_ID == Convert.ToInt32(ConfigurationManager.AppSettings["AREA_ID"].ToString())
                                         select new
                                         {
                                             a.AOS_ID,
                                             CABEZOTE = d.AMA_PLACA,
                                             TRAILER = r.AMA_PLACA,
                                             //ORIGEN = b.ACL_RAZON_SOCIAL,
                                             //DESTINO = c.ACL_RAZON_SOCIAL,

                                             a.AOS_FECHA_SOLICITUD,
                                             a.AOS_FECHA_ASIGNACION,
                                             a.AOS_FECHA_ENTREGA,
                                             AOS_ESTADO = f.AES_NOMBRE,
                                             CONDUCTOR = p.APE_NOMBRE
                                         };
                        foreach (var z in datosOrden)
                        {
                            //vines asociados a la orden
                            string strVines = "";
                            var datosVinLeberar = from a in contexto.AUT_ORDEN_SALIDA_AUT_VINs
                                                  where a.AOS_ID == z.AOS_ID
                                                  select a;

                            foreach (var j in datosVinLeberar)
                            {

                                var datosVin = from f in contexto.AUT_VINEs
                                               where f.AVI_ID == j.AVI_ID
                                               select f;
                                foreach (var o in datosVin)
                                {
                                    if (strVines == "")
                                        strVines = o.AVI_VIN;
                                    else
                                        strVines = strVines + ", " + o.AVI_VIN;
                                }
                            }

                            GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>TRAILER : </td><td>" + z.TRAILER + "</td></tr><tr><td>CONDUCTOR : </td><td>" + z.CONDUCTOR + "</td></tr>" + "</tr><tr><td>VINES : </td><td>" + strVines + "</td></tr>" + "</table>";
                            GP1.IconImage = "";
                        }
                        if (GP1.InfoHTML == "")
                        {
                            GP1.InfoHTML = "<table><tr><td>PLACA : </td><td>" + v.AMA_PLACA + "</td></tr><tr><td>SIN CARGA</td><td></td></tr></table>";
                            GP1.IconImage = "";
                        }


                        GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
                        
                    }


                }
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        PopupPanelMapa.Hide();
    }
}



